<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router'; // 导入 useRouter
import http from '@/utils/api.js';

// 获取路由参数
const route = useRoute();
const router = useRouter(); // 使用 useRouter 获取路由实例

const user = ref({
  id: '',
  username: '',
  password: '',
  phone: '',
  email: '',
  gender: '',
});

// 获取用户详情
async function loadUserDetails() {
  const userId = route.query.id; // 使用 route 获取 query 参数中的 id
  try {
    const response = await http.get(`/user/id/${userId}`);  // 根据 id 获取用户详情
    console.log(response)
    if (response.code===200) {
      user.value = response.data;  // 将返回的用户数据保存到 user 中
    } else {
      console.error("用户未找到");
    }
  } catch (error) {
    console.error("加载用户详情失败:", error);
  }
}

onMounted(() => {
  loadUserDetails();
});

// 提交修改后的用户数据
const handleSubmit = async () => {
  const id = user.value.id;
  if (id) {
    try {
      await http.post(`/user/edit/${id}`, user.value); // 提交修改后的用户数据
      alert('用户更新成功');
      router.push('/dashboard'); // 跳转回用户列表页面
    } catch (error) {
      console.error('更新用户失败:', error);
    }
  }
};
</script>

<template>
  <div>
    <el-form :model="user" ref="form" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="user.email"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="user.gender" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="user.phone"></el-input>
      </el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </el-form>
  </div>
</template>

<style scoped>
/* 你可以添加样式 */
</style>
